/*
* Copyright (c) 2016 . All Rights Reserved.
*/
package com.cgmnx.admin.web.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * @author: created  Date: 16/12/16 Time: 下午3:26
 * @version: 1.0
 */
@Slf4j
public class MonitorStatInterceptor implements HandlerInterceptor {

    private static final String MONITOR_KEY_TEMPLATE = "http%s";

    private static final String MONITOR_ATTRIBUTE_KEY = "cgmnx.http.monitor.startMillis";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        Long stateTime = System.currentTimeMillis();

        request.setAttribute(MONITOR_ATTRIBUTE_KEY, stateTime);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        Long startMillis = (Long) request.getAttribute(MONITOR_ATTRIBUTE_KEY);

        if (startMillis == null || !(handler instanceof HandlerMethod)) {
            return;
        }
        String key = replaceMonitorKey(request.getRequestURI());

        log.info("接口地址:[{}]执行时间:[{}]ms,请求参数:[{}]", String.format(MONITOR_KEY_TEMPLATE, key), System.currentTimeMillis() - startMillis, getRequestParam(request));

    }

    private StringBuilder getRequestParam(HttpServletRequest request) {
        Enumeration<String> keys = request.getParameterNames();

        StringBuilder parameterStr = new StringBuilder();

        while (keys.hasMoreElements()) {
            String k = keys.nextElement();
            parameterStr.append(k).append(" = ").append(request.getParameter(k)).append(";");
        }
        return parameterStr;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    private String replaceMonitorKey(String requestUri) {
        return StringUtils.replaceEach(StringUtils.lowerCase(requestUri), new String[]{"/", "."}, new String[]{"_", "_"});
    }
}